<?php
class PaymentModel extends Model {
	protected $_validate = array(
		array('paytypeid','require','款项必须！',1), 
		array('paymoney','require','金额必须！',1), 
		array('paymoney', 'number','金额为整数！', 1),
			
	);
	
	/**
	 * 卖家可用余额更新
	 * @param intval $paytypeid
	 * @param string $nick
	 * @param double $paymoney
	 * @return multitype:string |multitype:string number
	 */
	public function paymentUpdate( $paytypeid, $nick, $paymoney , $tid='', $trans=false){
		$s = D ( "Seller" );
		$p = D ( "Payment" );
		$ss = D ( "Sellersetting" );
		
		if (! $seller = $ss->getSellerByNick ( $nick )) {
			$result = array (
					'data' => '',
					'info' =>'卖家参数错误',
					'status' =>'0',
			);
			return $result;
		}
		
		if( $trans ) $s->startTrans ();
		
		$paytype = $ss->getPaytypeOne ( $paytypeid );
		if (! $paytype) {
			$result = array (
					'data' => '',
					'info' =>'款项参数错误',
					'status' =>'0',
					);
			return $result;
		}
			
		$pay ['paycode'] = $ss->createPayCode ();
		$pay ['tid'] = $tid;
		$pay ['user_id'] = $seller['id'];	//注意使用的是系统ID
		$pay ['nick'] = $nick;				//卖家昵称
		$pay ['paynick'] = $nick;			//操作人昵称
		$pay ['paytype'] = $paytype ['paytype'];
		$pay ['paymoney'] = $paymoney;
		$pay ['paymoneyresult'] = intval ( ($paytype ['paytype'] . '1') * $paymoney );
		$pay ['paycontent'] = $paytype['paytitle'];
		$pay ['paydate'] = date ( 'Y-m-d H:i:s' );
			
		$seller ['paybalance'] = $seller ['paybalance'] + $pay ['paymoneyresult'];
		if ($seller ['paybalance'] < 0) {
			$result = array (
					'data' => '',
					'info' =>'余额不足',
					'status' =>'0',
			);
			return $result;
		}
		$pay ['paymoneybalance'] = $seller ['paybalance'];
		// 充值记录
		$payresult = $p->add ( $pay );
		if ($payresult) {
				// 更新卖家余额
				$sellerresult = $s->where ( "id={$seller['id']} AND nick='{$nick}'" )->save ( $seller );
				if ($sellerresult) {
				if( $trans ) $s->commit ();
					$result = array (
							'data' => $pay,
							'info' => '款项更新成功',
							'status' =>'1',
					);
				}else{
				if( $trans ) $s->rollback ();
					$result = array (
							'data' => $pay,
							'info' => '款项更新失败'.D()->_sql().$paymoney,
							'status' =>'0',
					);
				}
				return $result;
		}else{
			$result = array (
					'data' => $pay,
					'info' => '日志错误',
					'status' =>'0',
			);
		}
		
		return $result;
	}
}